﻿using System.Diagnostics;
using System;
using BotDetector.Core.Detector;

namespace BotDetector.ConsoleApplication
{
    public class ArgParser
    {
        private const string tooManyParameters = "Too many parameters !";
        private const string googleEngine = "Google";
        private const string bingEngine = "Bing";
        private const string allEngine = "Bing&Google";
        private const string wrongParamater = "Wrong parameter !";
        private const string appFinishedErr = "Application finished with error";
        private const string appStarted = "Application started";
        private const string appFinished = "Application finished";
        private const string botMessage = "This is a bot";
        private const string notBotMessage = "This is not a bot";

        private bool goodParameters;
        private ResultAnalyzer executor = new ResultAnalyzer();

        public void Parse(string[] parameters)
        {
            goodParameters = true;
            try
            {
                Trace.WriteLine(string.Empty);
                Trace.WriteLine(appStarted);
                executor.phrase = parameters[1];
                ConfigureSearch(parameters);
                Trace.WriteLine(appFinished);           
            }
           catch (Exception ex)
           {
                Trace.WriteLine(ex.Message);
                Trace.WriteLine(appFinishedErr);
           }          
        }

        public void ConfigureSearch(string[] parameters)
        {
            if (parameters.Length == 2)
            {
                SelectSearchEngine(parameters);
                WriteResult();
            }
            else
            {
                Trace.WriteLine(tooManyParameters);
            }
        }

        private void WriteResult()
        {
            if (goodParameters)
            {
                if (executor.isBot)
                {
                    Trace.WriteLine(botMessage);
                }
                else
                {
                    Trace.WriteLine(notBotMessage);
                }
            }
        }

        public void SelectSearchEngine(string[] parameters)
        {         
            switch (parameters[0])
            {
                case googleEngine:
                    executor.GoogleExecute();
                    break;
                case bingEngine:
                    executor.BingExecute();
                    break;
                case allEngine:
                    executor.GoogleBingExecute();                                     
                    break;
                default:
                    Trace.WriteLine(wrongParamater);
                    goodParameters = false;
                    break;
            }
        }
    }
}
